import React, { Component } from 'react';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Button, Icon, Modal, Bubble, Tools, Progress } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';

import { TitleUtil } from '../../util';
import Api from '../../apis/setting';

const noop = () => { }
const { alert, prompt } = Modal;
const { getLabel } = Tools;

@inject('folderManageStore')
@withRouter
@observer
export default class FolderManage extends Component {

  prefixCls = "folder-manage";

  componentDidMount() {
		this.setState({ currentModel: {} });
    const { folderManageStore, title } = this.props
    const { listViewStore, template, folderCounts } = folderManageStore;
    listViewStore.setState({ template });
    listViewStore.clearData();
    this.getData();
    title && TitleUtil.setTitle(title);
    Api.getEmailSize().then(res => {
      const { occupyspace, totalSize, totalspace, unreadsize } = res;
      folderManageStore.setState({ folderCounts: { ...folderCounts, occupyspace, totalspace, unreadsize, totalSize } });
    });
  }

  componentWillUnmount() {
		let { currentModel } = this.state;
		currentModel && typeof currentModel.close === 'function' && currentModel.close();

    const { refreshList } = this.props;
    if (refreshList) {
      refreshList();
		}
  }

  getData = (current) => {
    const { folderManageStore } = this.props;
    const { listParams } = folderManageStore;
    folderManageStore.getData(listParams, current);
  }

  doAddFolder = () => {
		const { folderManageStore } = this.props;
    let currentModel = prompt(getLabel('18475', '新建文件夹'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: value => new Promise((resolve, reject) => {
        if (value.trim()) {
          folderManageStore.handleOperation({
            operation: 'add',
            folderName: value.trim(),
          });
          resolve();
        } else {
          Bubble.error(getLabel('384379', '您还有必填信息未填'), 1, { top: '10%' });
          reject();
        }
      })},
		], 'text-required', undefined, [getLabel('501571', '请输入文件夹名称')]);
		this.setState({currentModel: currentModel});
  }

  doEdit = (params) => {
    const { folderManageStore } = this.props;
    const { data: { folderName, randomFieldId } } = params;
    let currentModel = prompt(getLabel('31224', '编辑文件夹'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: value => new Promise((resolve, reject) => {
        if (value) {
          folderManageStore.handleOperation({
            operation: 'edit',
            folderName: value,
            folderId: randomFieldId,
          });
          resolve();
        } else {
          Bubble.error(getLabel('384379', '您还有必填信息未填'), 1, { top: '10%' });
          reject();
        }
      })},
		], 'text-required', folderName, [getLabel('501571', '请输入文件夹名称')]);
		this.setState({currentModel: currentModel});
  }

  doClearFolder = (params) => {
    const { folderManageStore } = this.props;
    const { data: { randomFieldId } } = params;
    let currentModel = alert(getLabel('510418','确定要清除该分类所有邮件的星标吗？'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () =>
        folderManageStore.handleOperation({
          operation: 'clearStar',
          folderId: randomFieldId,
        })
      },
		]);
		this.setState({currentModel: currentModel});
  }

  doDel = (params) => {
    const { folderManageStore } = this.props;
    const { data: { randomFieldId } } = params;
    let currentModel = alert(getLabel('510422','确定要删除文件夹吗？删除文件夹同时会删除邮件，删除的邮件可在垃圾箱里找到。'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () =>
        folderManageStore.handleOperation({
          operation: 'del',
          folderId: randomFieldId,
        })
      },
		]);
		this.setState({currentModel: currentModel});
  }

  doDelEmail = (params) => {
    const { folderManageStore } = this.props;
    const { data: { randomFieldId } } = params;
    let content = randomFieldId * 1 > 0 ? 
                    getLabel('510419','确定要删除该文件夹的所有邮件吗？删除的邮件可在垃圾箱里找到。') : 
                    getLabel('510420','确定要删除该分类的所有邮件吗？删除的邮件可在垃圾箱里找到。') 
    let currentModel = alert(content, '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () =>
        folderManageStore.handleOperation({
          operation: 'delmail',
          folderId: randomFieldId,
        })
      },
		]);
		this.setState({currentModel: currentModel});
  }

  doDelForever = (params) => {
    const { folderManageStore } = this.props;
    const { data: { randomFieldId } } = params;
    let currentModel = alert(getLabel('510421','确定要永久删除该文件夹的所有邮件吗？'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () =>
        folderManageStore.handleOperation({
          operation: 'deletePermanently',
          folderId: randomFieldId,
        })
      },
		]);
		this.setState({currentModel: currentModel});
  }

  renderOps = (o, check, data) => {
    const index = Number(o.index);
    let handler = noop;
    let icon = '';
    if (o.index * 1 === 0) { // edit
      handler = this.doEdit;
      icon = 'bianji';
    } else if (o.index * 1 === 1) { // clearStar
      handler = this.doClearFolder;
      icon = 'mail-clear';
    } else if (o.index * 1 === 2) { // delete
      handler = this.doDel;
      icon = 'delete';
    } else if (o.index * 1 === 3) { // delete email
      handler = this.doDelEmail;
      icon = 'delete';
    } else if (o.index * 1 === 4) { // delete email forever
      handler = this.doDelForever;
      icon = 'delete';
    }
    return (
      <span
        onClick={() => handler({ params: check[`randomFieldOpPara${index}`], data })}
        key={o.index}
        style={{ marginRight: 5 }}
      >
        {icon && <Icon type={icon}/>}
        {o.text}
      </span>
    );
  }

  renderChecks = (data) => {
    const { folderManageStore } = this.props;
    const { checks, ops } = folderManageStore;
    const check = toJS(checks.find(c => c.randomFieldId === data.randomFieldId));
    if (!check) { return null; }
    let opsCom = ops.map(o => {
      const randomFieldOp = JSON.parse(check.randomFieldOp);
      const index = Number(o.index);
      if (o && randomFieldOp[index]) {
        return this.renderOps(o, check, data);
      }
      return null;
    });
    return opsCom;
  }

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { id, folderNamespan, id_strspan, idspan } = data;
          return (
            <div className={`${this.prefixCls}-list-item`} key={id}>
              <div className={`${this.prefixCls}-list-item-name`}>
                <div className={`${this.prefixCls}-list-item-name-icon`}><Icon type="branch" /></div>
                <span>{folderNamespan}</span>
              </div>
              <div className={`${this.prefixCls}-list-item-size`}>
                <span>{getLabel(501569, '未读/总邮件数：')}{idspan}</span><span>{getLabel(83086, '占用空间：')}{id_strspan}</span>
              </div>
              <div className={`${this.prefixCls}-list-item-action`}>{this.renderChecks(data)}</div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  getPresent = (num, den) => {
    let persent = (num * 100 / den).toFixed(2);
    if (isNaN(persent)) { persent = 0; }
    return persent;
  }

  render() {
    const { folderManageStore: { listViewStore, folderCounts } } = this.props;
    const { unreadsize, totalSize, occupyspace, totalspace } = folderCounts;
    const sizePresent = this.getPresent(unreadsize, totalSize);
    const spacePresent = this.getPresent(occupyspace, totalspace);
    return (
      <div className={this.prefixCls}>
        <div className={`${this.prefixCls}-counts`}>
          <div className={`${this.prefixCls}-counts-item mailSize`}>
            <div className={`${this.prefixCls}-counts-item-progress ${sizePresent === 0 ? 'zero' : ''}`}>
              <Progress percent={sizePresent} position="normal" />
            </div>
            <div className={`${this.prefixCls}-counts-item-persent`}>{sizePresent}%</div>
            <div className={`${this.prefixCls}-counts-item-detail`}>{getLabel(27603, '未读邮件')}{unreadsize}{getLabel(83083, '封')}/{totalSize}{getLabel(83083, '封')}</div>
          </div>
          <div className={`${this.prefixCls}-counts-item mailSpace`}>
            <div className={`${this.prefixCls}-counts-item-progress ${spacePresent === 0 ? 'zero' : ''}`}>
              <Progress percent={spacePresent} position="normal" />
            </div>
            <div className={`${this.prefixCls}-counts-item-persent`}>{spacePresent}%</div>
            <div className={`${this.prefixCls}-counts-item-detail`}>{getLabel(34246, '邮箱空间')}{`${occupyspace}M/${totalspace}M`}</div>
          </div>
        </div>
        <div className={`${this.prefixCls}-list-view`}>
          <ListViewPage.Normal
            store={listViewStore}
            getDataCustom={true}
            getTemplate={this.getTemplate}
            onEndReached={this.getData}
            onRefresh={this.getData}
          />
        </div>
        <Button className="btn-add" icon="open" onClick={this.doAddFolder}>{getLabel('18475', '新建文件夹')}</Button>
      </div>
    );
  }
}
